//
//  ComposeView.swift
//  WeiboSwift
//
//  Created by Apple13 on 16/7/16.
//  Copyright © 2016年 yupeng. All rights reserved.
//

import UIKit

class ComposeView: UIView {
    
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 添加控件并且设置约束
    private func setUpUI() {
        
        self.frame.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        backgroundColor = RandomColor()
        
        addChildButton()
        
    }
    
    //添加6个子按钮
    private func addChildButton() {
        
        //按钮的宽度
        let buttonWidth:CGFloat = 80
        //按钮的高度
        let buttonHeight: CGFloat = 110
        //按钮之间的间距
        let itemMargin:CGFloat = (width - 3 * buttonWidth)/4
        
        //  获取plist里面的数据
        let composeMenuArray = loadComposePlist()

        
         for (i, value) in composeMenuArray.enumerate() {
            let button = ComposeMenuButton()
            button.size = CGSizeMake(buttonWidth, buttonHeight)
            
            //计算列索引
            let colIndex = i % 3
            //计算行索引
            let rowIndex = i / 3
            
            //计算X坐标
            button.x = buttonWidth * CGFloat(colIndex) + CGFloat(colIndex + 1) * itemMargin
            //计算Y坐标
            button.y = buttonHeight * CGFloat(rowIndex) + CGFloat(rowIndex) * itemMargin + 100
            
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            button.setTitle(value.Title, forState: .Normal)
            
            button.backgroundColor = UIColor.purpleColor()////‼️临时
            
            addSubview(button)
        }
        
        
    }
    
    
    //读取plist文件
    private func loadComposePlist() -> [ComposeMenu]{
        
        // 获取plist文件路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        //读取plist文件
        let composeDicArray = NSArray(contentsOfFile: path)!
        
        var tempArray = [ComposeMenu]()
        
        for dict in composeDicArray {
            let composeMenu = ComposeMenu(dict:dict as! [String : AnyObject])
            tempArray.append(composeMenu)
        }
        
        return tempArray
        
        
    }
   
    
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        removeFromSuperview()
    }
}
